const Router = require('@koa/router');
const path = require('path');

const uploadRouter = new Router({
    prefix: '/upload'
});

// 处理图片上传
uploadRouter.post('/', async (ctx) => {
    try {
        // 检查是否有上传的文件
        if (!ctx.request.files || !ctx.request.files.file) {
            ctx.status = 400;
            ctx.body = {
                status: 'error',
                message: '没有上传文件'
            };
            return;
        }
        
        const file = ctx.request.files.file;
        
        // 获取文件信息
        const fileName = path.basename(file.filepath || file.path);
        const fileUrl = `/ss/img/${fileName}`; // 构建文件访问URL
        
        ctx.status = 200;
        ctx.body = {
            status: 'success',
            url: fileUrl,
            message: '文件上传成功'
        };
    } catch (error) {
        console.error('Upload error:', error);
        ctx.status = 500;
        ctx.body = {
            status: 'error',
            message: '文件上传失败: ' + error.message
        };
    }
});

module.exports = uploadRouter;